-- 优惠券ID
local couponId = ARGV[1]
-- 用户ID
local userId = ARGV[2]

-- 优惠券库存
local stockKey = 'itbbs:coupon_stock:' .. couponId
-- 领取记录Key
local recordKey = 'itbbs:coupon_record:' .. couponId

-- 判断库存是否充足
if tonumber(redis.call('get', stockKey)) < 1 then
    return 1
end

-- 判断用户是否已经购买
if redis.call('sismember', recordKey, userId) == 1 then
    return 2
end

-- 扣减库存
redis.call('set', stockKey, redis.call('get', stockKey) - 1)
-- 添加领取记录
redis.call('sadd', recordKey, userId)
return 0